<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>主页</title>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="author" content="shiva"/>
    <meta name="renderer" content="webkit"/>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <link rel="stylesheet" type="text/css" th:href="@{/fms.css}" media="all">
    <script th:src="@{/static/plugin/vue.global.js}"></script>
    <link rel="stylesheet" type="text/css" th:href="@{/static/plugin/vant/index.css}" media="all">
    <script th:src="@{/static/plugin/vant/vant.min.js}"></script>
    <link rel="icon" th:href="@{/static/images/favicon.ico}" type="image/x-icon"/>
    <link rel="shortcut icon" th:href="@{/static/images/favicon.ico}"/>

    <script th:src="@{/static/plugin/jsencrypt.min.js}"></script>
    <script th:src="@{/static/common.js}"></script>
</head>
<body>
<div id="app">
    <input ref="token" name="token" th:value="${token}" type="hidden"/>
    <div style="position: fixed;top: 0; width: 100%;z-index: 999;">
        <van-search
                v-model="searchStr"
                placeholder="请输入搜索关键词"
                @search="onSearch"
                action-text="返回"
                show-action
                @cancel="back"
        ></van-search>
    </div>
    <div style="margin-top: 50px">
        <!-- 文件树的区域 -->
        <van-list
                v-model:loading="treeData.loading"
                :finished="treeData.finished"
                finished-text="全部资源都在这里了~"
                @load="onLoadTreeData"
        >
            <van-cell v-for="item in treeData.list" :key="item">
                <van-row>
                    <van-col span="2">
                        <div style="vertical-align: middle;line-height: 45px">
                            <img v-if="item.type == 'file'" src="/static/images/icon/file.png" style="height: 35px">
                            <img v-if="item.type == 'folder'" src="/static/images/icon/folder.png" style="height: 35px">
                        </div>
                    </van-col>
                    <van-col span="20">
                        <div style="text-align: left;margin-left: 15px" @click="pointItem(item)">
                            <div style="font-weight: bold">{{item.name}}</div>
                            <div style="font-size: 11px" v-if="currentStatus.searchResult">{{item.realPath}}</div>
                            <div>
                                <van-row gutter="20">
                                    <van-col span="18">
                                        <div class="label-container">
                                            <van-tag :type="randomType(index)" v-for="(lable, index) in item.labels">
                                                {{lable}}
                                            </van-tag>
                                        </div>
                                    </van-col>
                                    <van-col span="6" style="font-size: 12px;text-align: right" v-if="item.size > 0">
                                        {{item.size}} Kb
                                    </van-col>
                                </van-row>
                            </div>
                        </div>
                    </van-col>
                    <van-col span="2">
                        <div style="line-height: 45px;text-align: center" @click="openFunction(item)">
                            <van-icon name="ellipsis"/>
                        </div>
                    </van-col>
                </van-row>
            </van-cell>
        </van-list>
    </div>

    <!-- 底部弹窗 -->
    <van-action-sheet v-model:show="funcDialog.show">
        <div style="margin: 15px">
            <van-grid square :column-num="3">
                <van-grid-item icon="medal-o" text="下载" @click="download"
                               v-if="currentStatus.clickItem.type === 'file'" class="grid-blue"></van-grid-item>
                <van-grid-item icon="comment-o" text="打标签"></van-grid-item>
                <van-grid-item icon="setting-o" text="描述"></van-grid-item>
                <van-grid-item icon="aim" text="重命名" v-if="currentStatus.clickItem.type === 'file'"
                               @click="openRenameDialog(currentStatus.clickItem)" class="grid-blue"></van-grid-item>
                <van-grid-item icon="exchange" text="移动" v-if="currentStatus.clickItem.type === 'file'"
                               @click="openMoveDialog" class="grid-blue"></van-grid-item>
                <van-grid-item icon="delete-o" text="删除" @click="deleteNovel" class="grid-blue"></van-grid-item>
            </van-grid>
        </div>
    </van-action-sheet>

    <van-dialog v-model:show="moveFileDialog.show" title="选择移动文件夹"
                @confirm="actualMove"
                show-cancel-button>
        <div>
            <van-cell>
                <div style="text-align: left;margin-left: 15px" @click="nextFolder(moveFileDialog.rootObj)">
                    <div style="font-weight: bold">......</div>
                </div>
            </van-cell>
            <van-cell v-for="item in moveFileDialog.list" :key="item">
                <div style="text-align: left;margin-left: 15px" @click="nextFolder(item)">
                    <div style="font-weight: bold">{{item.name}}</div>
                </div>
            </van-cell>
        </div>
    </van-dialog>

    <van-dialog v-model:show="renameFile.show" title="重命名文件"
                @confirm="actualRename()"
                show-cancel-button>
        <input v-model="renameFile.value" placeholder="请输入新文件名" class="pwd-init-input"
               style="margin: 30px 30px 10px 30px;width: 80%"/>
        <div style="margin-left: 30px;color: #8f8f8f;font-size: 12px;padding-bottom: 10px">
            .txt 后缀自动拼接
        </div>
    </van-dialog>

    <van-floating-bubble icon="cluster" @click="morePage"></van-floating-bubble>
</div>
<script>
    Vue.createApp({
        el: '#app',
        data() {
            return {
                types: ["primary", "success", "warning", "danger"],
                requestHeaders: {},
                searchStr: '', //搜索框输入内容
                uploadNovelDialog: { //上传小说
                    open: false,
                },
                moveFileDialog: {
                    show: false,
                    list: [],//文件夹列表
                    pinkedFolderId: 0,//当前选中的文件夹ID
                    rootObj: {
                        id: 0
                    }
                },
                currentStatus: { //记录页面的基础状态
                    pageId: 0, //当前文件夹的ID，根目录为0；其他二级菜单都有上级目录
                    oldPageId: 0,//上一页的文件夹ID
                    clickItem: null, //当前点击得对象
                    searchResult: false, //当前列表是否是检索结果
                },
                treeData: {
                    list: [],
                    finished: false,
                    loading: false
                },
                funcDialog: {// 功能弹窗
                    show: false,
                },
                renameFile: {//重命名弹窗
                    show: false,
                    value: ''
                }
            }
        },
        created() {
            const that = this
            setTimeout(() => {
                that.token();
                //再计算RSA加密
                that.requestHeaders = commonHeaders()
            }, 200)
        },
        methods: {
            randomType(index) {
                return this.types[index % 4];
            },
            token() {
                const token = this.$refs.token.value
                if (token == null || token === '') {
                    return false;
                }
                //将token保存到缓存，使用 sessionStorage 存储数据
                sessionStorage.setItem('token', token);
                console.log('当前token:' + sessionStorage.getItem('token'))
            },
            morePage() {
                window.location.href = '/m/page?type=settings'
            },
            onSearch() {
                if (this.searchStr == null || this.searchStr.length === 0) {
                    vt4.showToast('请输入搜索内容');
                    return false
                }
                const that = this
                this.treeData.list = []
                //发请求，获取目录
                fetch('/api/novel/searchNovel?key=' + that.searchStr, {
                    method: 'GET',
                    headers: that.requestHeaders,
                }).then(response => response.json())
                    .then(data => {
                        that.currentStatus.searchResult = true;
                        // 数据全部加载完成
                        that.treeData.list = data.data
                        that.treeData.loading = false;
                        that.treeData.finished = true;
                    })

            },
            onLoadTreeData() {
                const that = this
                // 异步更新数据
                // setTimeout 仅做示例，真实场景中一般为 ajax 请求
                setTimeout(() => {
                    that.pageDataGet()
                }, 800);
            },
            //返回上一级
            back() {
                this.currentStatus.pageId = Number(this.currentStatus.oldPageId)
                this.currentStatus.oldPageId = 0;
                //清空数据先
                this.treeData.list = []
                this.pageDataGet()
            },
            //点击项。点文件夹，进入下一级；点文件，先在线打开
            pointItem(obj) {
                this.currentStatus.clickItem = obj
                if (obj.type === 'folder') {
                    this.currentStatus.oldPageId = Number(this.currentStatus.pageId)
                    this.currentStatus.pageId = obj.id;
                    //清空数据先
                    this.treeData.list = []
                    this.pageDataGet()
                    this.currentStatus.clickItem = null
                }
                if (obj.type === 'file') {//打开功能弹窗
                    this.funcDialog.show = true
                }
            },
            //打开底部功能区
            openFunction(obj) {
                this.currentStatus.clickItem = obj
                this.funcDialog.show = true
            },
            pageDataGet() {
                const that = this
                //发请求，获取目录
                fetch('/api/novel/pageNovelAndFolder?parentId=' + that.currentStatus.pageId, {
                    method: 'GET',
                    headers: that.requestHeaders,
                }).then(response => response.json())
                    .then(data => {
                        that.currentStatus.searchResult = false;
                        // 数据全部加载完成
                        that.treeData.list = data.data
                        that.treeData.loading = false;
                        that.treeData.finished = true;
                    })
            },
            //下载文件
            download() {
                const that = this
                //发请求，获取目录
                fetch('/api/novel/downloadFromOss?novelId=' + that.currentStatus.clickItem.id, {
                    method: 'GET',
                    headers: that.requestHeaders,
                }).then(response => response.json())
                    .then(data => {
                        const text = data.data.content;
                        const blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
                        const url = URL.createObjectURL(blob);

                        const downloadLink = document.createElement('a');
                        downloadLink.href = url;
                        downloadLink.download = data.data.name;
                        // downloadLink.click();
                        // 模拟点击事件
                        const clickEvent = new MouseEvent('click', {
                            view: window,
                            bubbles: true,
                            cancelable: true
                        });
                        downloadLink.dispatchEvent(clickEvent);
                        vt4.showToast('下载成功！');
                    })
            },
            //下载
            deleteNovel() {
                const that = this
                vt4.showConfirmDialog({
                    title: '确认删除？',
                    message: '删除后文件会先进入回收站',
                }).then(() => {
                    //发请求，获取目录
                    fetch('/api/novel/delete?novelId=' + that.currentStatus.clickItem.id, {
                        method: 'GET',
                        headers: that.requestHeaders,
                    }).then(response => response.json())
                        .then(data => {
                            vt4.showToast('删除成功！');
                            //移除当前行
                            that.treeData.list.splice(that.treeData.list.indexOf(that.currentStatus.clickItem), 1)
                            that.funcDialog.show = false
                        })
                }).catch(() => {
                });
            },
            //打开移动文件的窗口
            openMoveDialog() {
                this.moveFileDialog.pinkedFolderId = 0
                this.listFolderByParentId(this.moveFileDialog.pinkedFolderId)
                this.moveFileDialog.show = true
            },
            //点击文件夹，进入下一个文件夹
            nextFolder(obj) {
                this.moveFileDialog.pinkedFolderId = obj.id
                this.listFolderByParentId(this.moveFileDialog.pinkedFolderId)
            },
            //根据上级id拿到文件夹列表
            listFolderByParentId(parentId) {
                const that = this
                fetch('/api/novel/listFolder?parentId=' + parentId, {
                    method: 'GET',
                    headers: that.requestHeaders,
                }).then(response => response.json())
                    .then(data => {
                        that.moveFileDialog.list = data.data
                    })
            },
            //实际进行文件移动操作
            actualMove() {
                const that = this
                vt4.showConfirmDialog({
                    title: '确认移动',
                    message: '移动到新文件夹，当前路径会被移除',
                }).then(() => {
                    //发请求，获取目录
                    fetch('/api/novel/actualMove?folderId=' + that.moveFileDialog.pinkedFolderId + '&novelId=' + that.currentStatus.clickItem.id, {
                        method: 'GET',
                        headers: that.requestHeaders,
                    }).then(response => response.json())
                        .then(data => {
                            if (data.code === 200) {
                                vt4.showToast('移动成功！');
                                //移除当前行
                                that.treeData.list.splice(that.treeData.list.indexOf(that.currentStatus.clickItem), 1)
                                that.funcDialog.show = false
                            } else {
                                vt4.showToast(data.message);
                            }

                        })
                }).catch(() => {
                });
            },
            //打开重命名弹窗
            openRenameDialog(obj) {
                if (obj == null) {
                    return false;
                }
                this.renameFile.value = obj.name.replace(".txt", "")
                this.renameFile.show = true
            },
            //开始准备文件重命名流程
            actualRename() {
                const that = this
                fetch('/api/novel/renameFile?fileName=' + that.renameFile.value + '&novelId=' + that.currentStatus.clickItem.id, {
                    method: 'GET',
                    headers: that.requestHeaders,
                }).then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            vt4.showToast('重命名成功！');
                            //移除当前行
                            that.treeData.list[that.treeData.list.indexOf(that.currentStatus.clickItem)].name = that.renameFile.value + ".txt"
                            that.funcDialog.show = false
                        } else {
                            vt4.showToast(data.message);
                        }
                    })
            }
        }
    }).use(vant).mount("#app");
    const vt4 = vant;
</script>
</body>
</html>